package com.example.blackmarket.module.Me;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;

import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.example.blackmarket.R;
import com.example.blackmarket.module.Me.Recharge.AlipayActivity;
import com.example.blackmarket.entities.User;
import com.example.blackmarket.module.Base.BaseApplication;
import com.example.blackmarket.module.Me.Order.OrderActivity;
import com.example.blackmarket.module.RegisterAndLogin.LoginActivity;

import static android.app.Activity.RESULT_CANCELED;
import static android.app.Activity.RESULT_OK;

public class MeFragment extends Fragment implements MeView, View.OnClickListener {
    private ImageView userImage;
    private ImageView xiugai;
    private ImageView logout;
    private TextView username;
    private TextView userMail;
    private TextView userId;
    private TextView money;
    private View account;
    private View view;
    private View userAddress;
    private View order;
    private TextView campus;
    private TextView changeImageBtn;
    private View recharge;

    private User user;

    private static final int CHANGE_CODE = 517;
    private static final int RECHARGE_CODE = 188;

    private MePresenter mePresenter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_me, container, false);
        this.view = view;
        mePresenter = new MePresenter(MeFragment.this);
        onBindView();
        setButtonClick();
        getData();
        return view;
    }

    @Override
    public void getData() {
        mePresenter.getData();
    }

    @Override
    public void showData(Object data) {
        User user = (User) data;
        this.user = user;
        userMail.setText(user.getEmail());
        username.setText(user.getNickname());
        userId.setText(user.getStudentNumber());
        money.setText(String.format("%.2f", user.getBalance())+" 黑币");
        campus.setText(user.getCampus());
        Glide.with(this).load(user.getPictureAddress()).apply(RequestOptions.bitmapTransform(new CircleCrop())).into(userImage);
    }

    @Override
    public void changeImageSuccess() {
        showToast("修改头像成功！");
    }

    protected void onBindView(){
        userImage = view.findViewById(R.id.me_user_img);
        username = view.findViewById(R.id.me_user_name);
        userMail = view.findViewById(R.id.me_user_email);
        userId = view.findViewById(R.id.me_user_id);
        account = view.findViewById(R.id.account);
        money = account.findViewById(R.id.menu_item_hint);
        userAddress = view.findViewById(R.id.user_address);
        campus = userAddress.findViewById(R.id.menu_item_hint);
        xiugai = view.findViewById(R.id.xiugai);
        changeImageBtn = view.findViewById(R.id.change_image);
        order = view.findViewById(R.id.history_order);
        logout = view.findViewById(R.id.logout);
        recharge = view.findViewById(R.id.recharge);
    }

    public void setButtonClick(){
        changeImageBtn.setOnClickListener(this);
        userAddress.setOnClickListener(this);
        xiugai.setOnClickListener(this);
        order.setOnClickListener(this);
        logout.setOnClickListener(this);
        recharge.setOnClickListener(this);
    }

    public void onClick(View v) {
        switch (v.getId()){
            case R.id.user_address: {
                showToast("校区："+ user.getCampus() +" 详细地址：" + user.getAddress());
                break;
            }
            case R.id.xiugai:{
                changeInfo();
                break;
            }
            case R.id.change_image:{
                askForPermission();
//                pickImageFromAlbum();
                break;
            }
            case R.id.history_order:{
                Intent intent = new Intent(getContext(), OrderActivity.class);
                startActivity(intent);
                Log.e("meOrder","跳转至历史订单页面");
                break;
            }
            case R.id.logout:{
                AlertDialog.Builder dialog = new AlertDialog.Builder(getContext());
                dialog.setTitle("确认退出登录？");
                dialog.setMessage("请确认您的操作");
                dialog.setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        BaseApplication.set("token",null);
                        Intent intent = new Intent(getContext(), LoginActivity.class);
                        startActivity(intent);
                    }
                });
                dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                });
                dialog.show();
                break;
            }
            case R.id.recharge:
                Intent intent = new Intent(getContext(), AlipayActivity.class);
                startActivityForResult(intent,RECHARGE_CODE);
                break;
            default:{
                break;
            }
        }
    }

    public void showToast(String msg){
        Toast toast = Toast.makeText(getContext(), msg, Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.CENTER,0,0);
        toast.show();
    }

    public void changeInfo(){
        Intent intent = new Intent(getActivity(),ChangeInfoActivity.class);
        intent.putExtra("studentNumber",user.getStudentNumber());
        intent.putExtra("address",user.getAddress());
        intent.putExtra("nickname",user.getNickname());
        intent.putExtra("campus",user.getCampus());
        startActivityForResult(intent,CHANGE_CODE);
    }

    public void askForPermission(){
        if(ContextCompat.checkSelfPermission(getContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
//            Log.e("permission","ask for permission");
            ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},1);
        }else{
            pickImageFromAlbum();
        }
    }

    public void pickImageFromAlbum(){
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_PICK);
        //intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
        intent.setType("image/*");
        startActivityForResult(intent,111);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode){
            case 1:{
                if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                    pickImageFromAlbum();
                }else{
                    showToast("you denied the permission");
                }
                break;
            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            case 111:{
                if(resultCode == RESULT_CANCELED){
                    showToast("已取消选择");
                    return;
                }
                try{
                    Uri imageUri = data.getData();
                    String imagePath = getImagePath(imageUri);
                    mePresenter.upload(imagePath);
                    //Glide.with(this).load(imageUri).apply(RequestOptions.bitmapTransform(new CircleCrop())).into(userImage);

                }catch (Exception e){
                    e.printStackTrace();
                }
                break;
            }
            case CHANGE_CODE:{
                if(resultCode == RESULT_OK){
                    String newAddress = data.getStringExtra("address");
                    String newNickname = data.getStringExtra("nickname");
                    String newCampus = data.getStringExtra("campus");
                    user.setAddress(newAddress);
                    user.setCampus(newCampus);
                    user.setNickname(newNickname);
                    username.setText(newNickname);
                    campus.setText(newCampus);
                }
            }
            case RECHARGE_CODE:
                if (resultCode == RESULT_OK) {
                    getData();
                }
            default:
                break;

        }
    }

    private  String getImagePath(Uri uri) {
        String path = null;
        Cursor cursor = getContext().getContentResolver().query(uri, null, String.valueOf(new String[]{MediaStore.Images.ImageColumns.DATA}), null, null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }


}